package com.jcz.daoImpl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;

import com.jcz.dao.HibernateUtil;
import com.jcz.dao.Vote_OptionDao;
import com.jcz.entity.Vote_Option;

public class Vote_OptionDaoImpl implements Vote_OptionDao {

	/*按题目id查找选项*/
	@Override
	public List<Vote_Option> findBySubject(Integer vs_id) {
		Session session=null;
		List<Vote_Option> list=null;
		
		try {
			session=HibernateUtil.currentSession();
			list=session.createQuery("select o from Vote_Option"+"where o.vs_id=:id")
			.setParameter("id", vs_id)
			.list();
			
			
		} catch (Exception e) {			
			e.printStackTrace();			
		}
		return list;
	}


	/*添加选项*/
	@Override
	public boolean addOption(Vote_Option option) {
		Session session=null;
		Transaction tx=null;
		
		try {
			session=HibernateUtil.currentSession();
			tx=session.beginTransaction();
			
			session.save(option);
			
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return false;
		}
		return true;	
	}

	/*更新选项*/
	@Override
	public boolean updateOption(Vote_Option option) {
		Session session=null;
		Transaction tx=null;
		
		try {
			session=HibernateUtil.currentSession();
			tx=session.beginTransaction();
			
			/*session.update(option);*/
			session.saveOrUpdate(option);
			
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return false;
		}
		return true;
	}

	/*删除选项*/
	@Override
	public boolean delOption(Integer vo_id) {
		Session session=null;
		Transaction tx=null;
		
		try {
			session=HibernateUtil.currentSession();
			tx=session.beginTransaction();
			
			Vote_Option option=(Vote_Option)session.get(Vote_Option.class, vo_id);
			session.delete(option);
			
			tx.commit();
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			return false;
		}
		return true;
	}


	@Override
	public long findCount(Integer id) {
		Session session=null;
		long optionCount=0;
		
		try {
			session=HibernateUtil.currentSession();
			Criteria criteria=session.createCriteria(Vote_Option.class);
			criteria.add(Restrictions.eq("vote_Subject.vs_id", id))
			.setProjection(Projections.count("vo_id"));
			optionCount=(long)criteria.uniqueResult();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return optionCount;
	}

}
